package gruppe7.control;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ServletController {

	private static String PwCookieName = "pwCookie";
	private static String UserCookieName = "userCookie";
	
	private static ServletController instance = new ServletController();
	
	public static ServletController getInstance() {
		return instance;
	}
	
	private ServletController() {
		
	}
	
	public Session getSession(HttpServletRequest request, HttpServletResponse response) {
		return new Session(request, response);
	}
	
	public boolean isSessionCreated(HttpServletRequest request) {
		HttpSession httpSession = request.getSession(false);
		
		if (httpSession != null) {
			String key = Session.UserKey;
			return httpSession.getAttribute(key) != null;
		}
		
		else return false;
	}
	
	public void sendToErrorPage(HttpServletResponse response) {
		
		try {
			response.sendError(500);
		}
		
		catch (Exception e) {
			// hmm - hvad gør man så?
			System.err.println(e.getStackTrace());
		}	
	}
	
	public String getUsernameCookieValue(HttpServletRequest request) {
		return getCookieValue(request, UserCookieName);
	}
	
	public String getPasswordCookieValue(HttpServletRequest request) {
		return getCookieValue(request, PwCookieName);
	}
	
	public void setUsernameCookie(HttpServletResponse response, String value) {
		Cookie cookie = new Cookie(UserCookieName, value);
		cookie.setMaxAge(60 * 60 * 24);
		
		response.addCookie(cookie);
	}
	
	public void setPasswordCookie(HttpServletResponse response, String value) {
		Cookie cookie = new Cookie(PwCookieName, value);
		cookie.setMaxAge(60 * 60 * 24);
		
		response.addCookie(cookie);
	}
	
	public void deleteUsernameCookie(HttpServletResponse response) {
		deleteCookie(response, UserCookieName);
	}
	
	public void deletePasswordCookie(HttpServletResponse response) {
		deleteCookie(response, PwCookieName);
	}
	
	private void deleteCookie(HttpServletResponse response, String name) {
		Cookie cookie = new Cookie(name, null);
		cookie.setMaxAge(0);
		
		response.addCookie(cookie);
	}
	
	private String getCookieValue(HttpServletRequest request, String name) {
		String value = null;
		boolean found = false;
	    Cookie[] cookies = request.getCookies();
	    int idx = 0;

	    if (cookies == null) return value;
	    
	    while (!found && idx < cookies.length) {
	    	Cookie cookie = cookies[idx];
	        	
	    	if (cookie.getName().equals(name)) {
	    		value = cookie.getValue();
	    		found = true;
	    	}
	        	
	    	idx ++;
	    }
	    
	    return value;
	}
	
	
	
}
